import urllib.request as req
import json

class onenet(object):
    def __init__(self):
        pass

    def OneNet_post_data(self,info):
        url = "https://api.heclouds.com/devices/" + info[0] + '/datapoints'
        headers = {'api-key': info[1]}
        streams = []
        for i, e in enumerate(info[2]):
            streams.append({"id": e[0], "datapoints": [{"value": e[1]}]})
        data = json.dumps({"datastreams": streams}).encode("utf-8")
        request = json.loads((req.urlopen(req.Request(url, data, headers=headers))).read())
        print(request)
    '''
        OneNet_post_data(info)
        info类型举例
        upload_data = [ ["road1", 10],["road2", 20]]
    '''

    def OneNet_get_data(self,info):
        url = "http://api.heclouds.com/devices/" + info[0] + "/datastreams"
        headers = {'api-key': info[1]}
        request = json.loads((req.urlopen(req.Request(url, headers=headers))).read())
        data = request.pop('data')
        print(request)

        return data
    '''
    传入参数：[deviceId, APIKey]
    返回的是json串[{key,time,value}]
    '''